import { _decorator, Component, Node, Button, Label, director } from 'cc';
import { GameManager, GameEvent } from './GameManager';

const { ccclass, property } = _decorator;

@ccclass('FasterManager')
export class FasterManager extends Component {
    @property({ type: Button, tooltip: "加速按钮（减少flipDuration）" })
    fasterButton!: Button;

    @property({ type: Node, tooltip: "硬币父节点（用于统计硬币数量）" })
    coinsParent!: Node;

    @property({ type: Number, tooltip: "每次点击减少的百分比（%）", step: 1, min: 1, max: 50 })
    reducePercentPerClick = 5; // 每次减少初始时间的5%

    @property({ type: Number, tooltip: "翻转时间最小限制（秒）", min: 0.1 })
    minFlipDuration = 0.1;

    // 缓存属性
    private gameManager!: GameManager;
    private fasterBtnLabel!: Label;
    private currentCostScore = 1; // 当前加速消耗的分数
    private initialFlipDuration = 2; // 从GameManager读取的初始翻转时间
    private reduceAmountPerClick = 0; // 每次实际减少的时间（秒）
    private accelerateCount = 0; // 已加速次数（核心新增）

    onLoad() {
        this.initGameManager();
        this.calculateReduceAmount();
        this.initButtonLabel();
        this.updateCostScore(); // 初始化成本（基于初始加速次数0）
        this.updateButtonText();
    }

    start() {
        this.bindButtonEvent();
        this.listenCoinCountChange(); // 硬币数量变化时更新成本
        this.listenScoreUpdate(); // 分数不足时按钮置灰
    }

    // 初始化GameManager并读取初始翻转时间
    private initGameManager() {
        const gameManagerNode = director.getScene().getChildByName("Canvas").getChildByName("GameManager");
        this.gameManager = gameManagerNode?.getComponent(GameManager);
        if (!this.gameManager) {
            console.error("FasterManager: 未找到GameManager节点！");
            return;
        }

        // 读取GameManager的初始翻转时间作为基准
        this.initialFlipDuration = this.gameManager.flipDuration;
        if (this.initialFlipDuration <= 0) {
            this.initialFlipDuration = 2;
            console.warn(`FasterManager: 使用默认初始翻转时间${this.initialFlipDuration}秒`);
        }
        console.log(`FasterManager: 初始翻转时间=${this.initialFlipDuration}秒`);
    }

    // 计算每次减少的实际时间（初始时间×百分比）
    private calculateReduceAmount() {
        this.reduceAmountPerClick = this.initialFlipDuration * (this.reducePercentPerClick / 100);
        console.log(`FasterManager: 每次加速减少${this.reducePercentPerClick}%，即${this.reduceAmountPerClick.toFixed(2)}秒`);
    }

    // 初始化按钮Label组件
    private initButtonLabel() {
        if (!this.fasterButton) {
            console.error("FasterManager: 未绑定Faster按钮！");
            return;
        }
        this.fasterBtnLabel = this.fasterButton.node.getChildByName("Label")?.getComponent(Label);
        if (!this.fasterBtnLabel) {
            console.error("FasterManager: 按钮子节点\"Label\"未添加Label组件！");
        }
    }

    // 绑定按钮点击事件
    private bindButtonEvent() {
        if (this.fasterButton) {
            this.fasterButton.node.on(Button.EventType.CLICK, this.onFasterClick, this);
        }
    }

    // 监听硬币数量变化（更新成本）
    private listenCoinCountChange() {
        if (this.coinsParent) {
            this.coinsParent.on(Node.EventType.CHILD_ADDED, this.updateCostScore, this);
            this.coinsParent.on(Node.EventType.CHILD_REMOVED, this.updateCostScore, this);
        } else {
            console.error("FasterManager: 未绑定硬币父节点！");
        }
    }

    // 监听分数更新（按钮状态）
    private listenScoreUpdate() {
        if (this.gameManager?.scoreNode) {
            this.gameManager.scoreNode.on(GameEvent.SCORE_UPDATED, (currentScore: number) => {
                this.updateButtonState(currentScore);
            }, this);
        }
    }

    // 核心修改：计算当前加速成本 = 硬币数量 × (2 + 已加速次数)
    private updateCostScore() {
        if (!this.coinsParent) return;

        // 统计有效硬币数量
        const validCoinCount = this.coinsParent.children.filter(
            child => child.getComponent("CoinManager") !== null
        ).length;

        // 计算成本：无硬币时默认1分，否则按公式计算
        this.currentCostScore = validCoinCount > 0 
            ? validCoinCount * (2 + this.accelerateCount) 
            : 1;

        this.updateButtonText(); // 同步按钮文本

        const currentScore = this.gameManager.getCurrentScore();
        this.updateButtonState(currentScore);
    }

    // 更新按钮文本（显示“加速X%-Y分”）
    private updateButtonText() {
        if (this.fasterBtnLabel) {
            this.fasterBtnLabel.string = `加速${this.reducePercentPerClick}%-${this.currentCostScore}分`;
        }
    }

    // 分数不足时按钮置灰
    private updateButtonState(currentScore: number) {
        if (this.fasterButton) {
            this.fasterButton.interactable = currentScore >= this.currentCostScore;
        }
    }

    // 加速按钮核心逻辑（含次数累计）
    private onFasterClick() {
        if (!this.gameManager) return;

        // 1. 分数校验
        const currentScore = this.gameManager.getCurrentScore();
        if (currentScore < this.currentCostScore) {
            console.warn(`FasterManager: 分数不足！需${this.currentCostScore}分，当前${currentScore}分`);
            return;
        }

        // 2. 扣分
        this.gameManager.deductScore(this.currentCostScore);

        // 3. 计算新的翻转时间
        const newFlipDuration = Math.max(
            this.minFlipDuration,
            this.gameManager.flipDuration - this.reduceAmountPerClick
        );
        this.gameManager.flipDuration = newFlipDuration;

        // 4. 累计加速次数（核心：下次成本会增加）
        this.accelerateCount++;
        console.log(`FasterManager: 已加速${this.accelerateCount}次`);

        // 5. 广播配置，同步硬币
        this.gameManager.broadcastConfig();

        // 6. 重新计算下次加速成本（因次数增加）
        this.updateCostScore();

        console.log(
            `加速成功！当前翻转时间=${newFlipDuration.toFixed(2)}秒，下次加速成本=${this.currentCostScore}分`
        );

        // this.updateButtonState(currentScore);
    }

    // 编辑器修改属性时重新计算
    onPropertyChanged() {
        this.reducePercentPerClick = Math.max(1, Math.min(50, this.reducePercentPerClick));
        this.calculateReduceAmount();
        this.updateButtonText();
    }

    // 游戏重置时恢复加速次数（可选，需监听GameEvent.GAME_RESET）
    private resetAccelerateCount() {
        this.accelerateCount = 0;
        this.updateCostScore(); // 重置成本
        console.log("FasterManager: 游戏重置，加速次数清零");
    }

    onEnable() {
        // 监听游戏重置事件（若有）
        this.gameManager?.node.on(GameEvent.GAME_RESET, this.resetAccelerateCount, this);
    }

    onDestroy() {
        // 清理事件监听
        if (this.fasterButton) {
            this.fasterButton.node.off(Button.EventType.CLICK, this.onFasterClick, this);
        }
        if (this.coinsParent) {
            this.coinsParent.off(Node.EventType.CHILD_ADDED, this.updateCostScore, this);
            this.coinsParent.off(Node.EventType.CHILD_REMOVED, this.updateCostScore, this);
        }
        if (this.gameManager?.scoreNode) {
            this.gameManager.scoreNode.off(GameEvent.SCORE_UPDATED, this.updateButtonState, this);
        }
        this.gameManager?.node.off(GameEvent.GAME_RESET, this.resetAccelerateCount, this);
    }
}